import {Component, ViewChildren, ViewChild, ChangeDetectorRef, ElementRef} from '@angular/core';
import {Content, IonicPage, NavController, NavParams} from 'ionic-angular';
import {ContactsProvider} from '../../providers/contacts/contacts'
import * as _ from 'lodash';

/**
 * Generated class for the CustomListBetaPage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-custom-list-beta',
  templateUrl: 'custom-list-beta.html',
})
export class CustomListBetaPage {

    index: string = 'A';
    showModal: boolean = false;
    timeout: any;
    indexes: Array<string> = "ABCDEFGHIJKLMNOPQRSTUVWXYZ#".split('');
    offsetTops: Array<number> = [];
    contacts: Array<any> = [];
    getOk:boolean=false;

    @ViewChildren('IonItemGroup') ionItemGroup;
    @ViewChild(Content) content: Content;

    constructor(public navCtrl: NavController,
                public contactsSev: ContactsProvider,
                public ref: ChangeDetectorRef,
                private _elementRef: ElementRef
                ) {

        this.contactsSev.getContacts()
            .subscribe(res => {
                this.contacts = this.contactsSev.grouping(res);
            },()=>{

            },()=>{
                //请求完成后稍微等待视图渲染完成
                console.log('ok');
                setTimeout(()=>{
                    this.getOk=true;
                    this.getOffsetTops();
                },100);
            })
    }

    ionViewDidEnter() {

    }

    unread(){

    }

    /**
     * 获取元素的offsetTop
     */
    getOffsetTops() {
        this.offsetTops = this.ionItemGroup._results.map(ele => {
            return ele.nativeElement.offsetTop
        });
        this.setupHammerHandlers();
    }

    /**
     * 设置手势上下
     */
    setupHammerHandlers() {
        let sidebarEle: HTMLElement = this._elementRef.nativeElement.querySelector('.indexed-menu');

        if (!sidebarEle) return;

        let mcHammer = new Hammer(sidebarEle, {
            recognizers: [
                // RecognizerClass, [options], [recognizeWith, ...], [requireFailure, ...]
                [Hammer.Pan, {direction: Hammer.DIRECTION_VERTICAL}],
            ]
        });


        mcHammer.on('panup pandown', _.throttle((e: any) => {
            const closestEle: any = document.elementFromPoint(e.center.x, e.center.y);
            if(closestEle&&closestEle.innerText){
                this.selectIndex(this.indexes.indexOf(closestEle.innerText));
            }
        }, 50));
    }

    /**
     * 设置列表位置
     * @param {number} index
     */
    selectIndex(index: number) {
        this.index = this.indexes[index];
        const offsetTop = this.offsetTops[index];
        this.content.scrollTop=offsetTop
    }


    onScroll() {

        const threshold = 42;

        if (this.content.scrollTop < threshold) {
            this.index = this.indexes[0];
            return;
        }

        for (let i = this.offsetTops.length; i > 0; i--) {
            if (this.content.scrollTop + threshold >= this.offsetTops[i]) {
                this.index = this.indexes[i];
                this.ref.detectChanges();
                return;
            }
        }
    }

    /**
     * 字母弹框
     */
    createModal() {
        clearTimeout(this.timeout);
        this.showModal = true;
        this.timeout = setTimeout(() => {
            this.showModal = false;
            this.ref.detectChanges();
        }, 800)
    }

}
